'use strict';

const Service = require('egg').Service;

class UserService extends Service {

  /**
   * 用户列表
   * @param page
   * @param pageSize
   * @returns {Promise<{list: {rows: TInstance[]; count: number}}>}
   */
  async list(page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = parseInt((page - 1) * pageSize);
    const list = await ctx.model.User.findAndCountAll({
      orders: [
        [ 'id', 'desc' ],
      ],
      limit: parseInt(pageSize),
      offset,
    });
    return {
      list,
    };
  }

  // 登陆
  async find(username, password) {
    const { ctx } = this;
    const result = await ctx.model.User.findOne({
      where: {
        username,
        password,
      },
    });
    return result;
  }

  // 根据id查找
  findId(id) {
    const { ctx } = this;
    const result = ctx.model.User.findOne({
      where: {
        user_id: id,
      },
    })
    return result;
  }

  async update({
    user_id,
    name,
    username,
    password,
    avatar,
    status,
    telephone,
    last_login_at,
    last_login_ip,
    role_id,
    created_at,
  }) {
    const { ctx } = this;
    const result = await ctx.model.User.update({
      user_id,
      name,
      username,
      password,
      avatar,
      status,
      telephone,
      last_login_at,
      last_login_ip,
      role_id,
      created_at,
    }, {
      where: {
        user_id,
      },
    });
    return result ? 'success' : 'fail';
  }

  // 新增
  async create() {
    const { ctx } = this;
    const body = ctx.request.body;
    const result = await ctx.model.User.create(body);
    return result ? 'success' : 'fail';
  }
}

module.exports = UserService;
